package com.qujia.station.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.BaseException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.station.domain.Repositories;
import com.qujia.station.mapper.StationMapper;
import com.qujia.station.service.RepositoryService;
import com.qujia.station.utils.CodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service("repositoryService")
@Slf4j
public class RepositoryServiceImpl implements RepositoryService {

    @Autowired
    private StationMapper stationMapper;

    @Override
    public int saveRepository(Repositories repository) {
        String code = CodeUtil.stationCode();
        repository.setStationCode(code);
        repository.setEnterpriseId(-1L);
        repository.setStatus("1"); // 默认开启
        repository.setCreateDate(new Date());
        repository.setIsRepository("1"); // 仓库标识
        int i = stationMapper.insertRepositories(repository);
        if(i <= 0){
            throw new BaseException("新增仓库失败");
        }
        return i;
    }

    @Override
    public List<Repositories> selectRepositoryList(Repositories repository) {
        return stationMapper.selectRepositoriesList(repository);
    }

    @Override
    public Repositories selectOneRepository(Repositories repository) {
        List<Repositories> repositories = stationMapper.selectRepositoriesList(repository);
        if(CollectionUtil.isEmpty(repositories)){
            throw new BaseException("仓库不存在");
        }
        return repositories.get(0);
    }

    @Override
    public int updateRepository(Repositories repository) {
        repository.setUpdatedTime(new Date());
        return stationMapper.updateRepositories(repository);
    }

    @Override
    public void deleteRepository(List<Long> stationIdList) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        Repositories repositories = new Repositories();
        repositories.setStationIdList(stationIdList);
        List<Repositories> repositoriesList = stationMapper.selectRepositoriesList(repositories);
        for (Repositories repository : repositoriesList) {
            repository.setDeleteStatus("1");
            repository.setStatus("1");
            repository.setDeleteDate(new Date());
            repository.setDeleteUser(sysUser.getUserId());
            stationMapper.updateRepositories(repository);
        }
    }
}
